USER=`/usr/ucb/whoami`
CRONLOC=/var/spool/cron/crontabs
CRONCOMMFILE=/tmp/cron_comm_file.sh
CRONGREP=`crontab -l | grep sys_diag`


mkdir cron
echo <<EOF
#!/usr/bin/ksh
###############################################################################
# File: purgelogs.sh
# Desc: Removes logs older than the number of days passed in as first arg
# 
############################################################################### 


if [[ $# < 1 ]]; then   
        echo "Usage $0 DAYS"    
        exit 2
fi      

SERVERS_DIR=/opt/apps/afls/wls103_afls/domains/AflsAdmServer/servers

echo "Looking for logs older than $1 days"
for server in `ls $SERVERS_DIR`
        do
                if [[ $server != "domain_bak" ]]; then
                        find $SERVERS_DIR/$server/logs/ -name '*.log*' -mtime +$1 -exec rm {} \;
                fi
        done
EOF >> purgeLogs.sh

chmod +x purgeLogs.sh
  
################################# INSTALL THE CRONJOB
if [ "$CRONGREP" != "" ];
then
echo "Crontab already exists"
exit 
fi
#
# Create command file to create crontab file
#
# If command files already exists delete it
#
if [ -f $CRONCOMMFILE ]; then
  rm -f $CRONCOMMFILE
fi

CRONLINE="0 0 * * * export MAILTO='koy.dooley@aa.com' && /opt/apps/afls/wls103_afls/cron/purgeLogs.sh 7"

#
# Added commands into the file to create the crontab entry
#

echo "#!/bin/sh" >> $CRONCOMMFILE
echo "EDITOR=ed" >> $CRONCOMMFILE
echo "export EDITOR" >> $CRONCOMMFILE


echo "crontab -e $USER << EOF > /dev/null" >> $CRONCOMMFILE
echo "a" >> $CRONCOMMFILE
echo "$CRONLINE" >> $CRONCOMMFILE
echo "." >> $CRONCOMMFILE
echo "w" >> $CRONCOMMFILE
echo "q" >> $CRONCOMMFILE
echo "EOF" >> $CRONCOMMFILE

chmod 750 $CRONCOMMFILE

#
# Execute the the crontab command file
#
if [ -f $CRONCOMMFILE ]; then
  $CRONCOMMFILE
  rm $CRONCOMMFILE
else
  echo "Error: File generated to create crontab entry does not exist"
  exit 1
fi

echo "Crontab Entry Inserted Successfully"
#